package com.x.ant.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;

public class Base64Image {
    public static boolean generateImage(String base64Str, String filePath, String fileName) throws Exception {
        boolean flag = false;
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bytes = decoder.decodeBuffer(base64Str);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {
                    bytes[i] += 256;
                }
            }
            File dir = new File(filePath);
            if (!dir.exists()) {
                dir.mkdir();
            }
            dir = new File(dir, fileName);
            OutputStream out = new FileOutputStream(dir);
            out.write(bytes);
            out.flush();
            out.close();
            flag = true;
        } finally {
            return flag;
        }
    }

    public static String getImageStr(String imgFile) {
        InputStream inputStream = null;
        byte[] data = null;
        try {
            inputStream = new FileInputStream(imgFile);
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 加密
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }

    public static void main(String[] args) throws Exception {
//        String strImg = getImageStr("D:/728070229615249389.jpg");
//        System.out.println(strImg);
        String a = "";
        System.out.print(a.length());
        generateImage(a, "D:/", "x.jpg");
    }
}
